var express = require('express');
var router = express.Router();
var catemodel = require('../db/cate')
var usermodel = require("../db/user")
var qstmodel= require("../db/questions")
var jwt = require("jsonwebtoken")
var mianmodel=require('../db/mian')
var testmodel=require('../db/test')
var kaomodel=require("../db/kaoshi")
const multer  = require('multer')
const upload = multer({ dest: './public/media/' })
const path=require("path")
var fs = require("fs")
/* GET home page. */
router.get('/', function(req, res, next) {
  res.render('index', { title: 'Express' });
});
// 登录
router.post('/login',async function(req,res){
  console.log(1111111111111111111111)
  var user=await usermodel.find({user:req.body.user,password:req.body.password})
  console.log(user)
  if(user[0].role=='管理员'){
    console.log(11111)
    var token = jwt.sign({
      data: 'admin'
    }, 'secret', { expiresIn: '30000s' },httpOnly=true);  
    res.json({"message":"登录成功",'code':200,token:'Bearer'+' '+token})
  }else if(user[0].role=='普通用户'){
    console.log(222222)
    var token = jwt.sign({
      data: 'normal'
    }, 'secret', { expiresIn: '30000s' },httpOnly=true);  
    res.json({"message":"登录成功",'code':200,token:'Bearer'+' '+token})
  }else{
    res.json({"message":"登录失败",'code':404})
  }

})

router.post('/vue-element-admin/user/login',async function(req,res){
    var user=await usermodel.find({user:req.body.username,password:req.body.password})
    console.log(user)
    if(user[0].role=='管理员'){
      res.json({code:20000,data:{token:"admin"}})
    }else if(user[0].role=='普通用户'){
      res.json({code:20000,data:{token:"editor"}})
    }  
})

router.get('/vue-element-admin/user/info',function(req,res){
  if(req.query.token=='admin'){
      res.json({code:20000,data:{
        roles: ['admin'],
        introduction: 'I am a super administrator',
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        name: 'Super Admin'
      }})
  }else if(req.query.token=='editor'){
      res.json({code:20000,data:{
        roles: ['editor'],
        introduction: 'I am a super administrator',
        avatar: 'https://wpimg.wallstcn.com/f778738c-e4f8-4870-b634-56703b4acafe.gif',
        name: 'Super Admin'
      }})
  }
})

router.post('/vue-element-admin/user/logout',function(req,res){
  res.json({
      code: 20000,
      data: 'success'
  })
})
// 分类添加
router.post('/cate',async function(req,res){
  var data=await catemodel.create(req.body)
  res.json({"message":"添加成功","code":200,"data":data})
})
// 分类获取 模糊查询
router.get('/cate',async function(req,res){
  var search=req.query.search
  var page=parseInt(req.query.page) 
  var size=parseInt(req.query.size)
  if(search){
    var reg=new RegExp(search,'i')
    var data=await catemodel.find({cateName:{$regex:reg},status:1}).limit(size).skip((page-1)*size)
    var total=await catemodel.find({cateName:{$regex:reg},status:1}).count()
    console.log(data)
  }else{
    var data=await catemodel.find().limit(size).skip((page-1)*size)
    var total=await catemodel.find().count()
  }
  res.json({"message":"获取成功","code":200,"data":data,"total":total})
})
// 获取全部分类
router.get('/cateall',async function(req,res){
  var data=await catemodel.find({status:1})
  res.json({"message":"获取成功","code":200,"data":data})
})
// 修改分类信息
router.put('/cate/:_id',async function(req,res){
  var data=await catemodel.updateOne(req.params,req.body)
  res.json({"message":"修改成功","code":200,"data":data})
})
// 删除分类
router.delete('/cate/:_id',async function(req,res){
  if(req.user.data!='admin'){
    res.json({"message":"没有权限","code":400})
  }else{
    var data=await catemodel.deleteOne(req.params)
    res.json({"message":"删除成功","code":200})
  }

})
// 获取用户
router.get('/user',async function(req,res){
  var page=parseInt(req.query.page) 
  var size=parseInt(req.query.size)
  var d=await usermodel.find().limit(size).skip((page-1)*size)
  var total=await usermodel.find().count()
  res.json({"message":"获取成功","code":200,"data":d,"total":total})
})
// 添加用户
router.post('/user',async function(req,res){
  var d=await usermodel.create(req.body)
  res.json({"message":"获取成功","code":200})
})
// 修改用户
router.put('/user/:_id',async function(req,res){
  var d=await usermodel.updateOne(req.params,req.body)
  res.json({"message":"修改成功","code":200})
})
// 删除用户
router.delete('/user/:_id',async function(req,res){
  if(req.user.data!='admin'){
    res.json({"message":"没有权限","code":400})
  }else{
    var data=await usermodel.deleteOne(req.params)
    res.json({"message":"删除成功","code":200})
  }
})
// 添加题目
router.post('/question',async function(req,res){
  var d=await qstmodel.create(req.body)
  res.json({"message":"添加成功","code":200,"data":d})
})
// 获取题目
router.get('/question',async function(req,res){
  var page=parseInt(req.query.page) 
  var size=parseInt(req.query.size)

  if(req.query._id){
    // 分类
    var d=[]
    var t=await qstmodel.find().populate('cate')
    t.forEach((item)=>{
      if(item.cate.id==req.query._id){
        d.push(item)
      }
    })
    var total=d.length
  }else if(req.query.title && req.query.status==''){
    // 查询题目 当只搜索标题时
    var reg = new RegExp(req.query.title,'i')
    var d=await qstmodel.find({title:{$regex:reg}}).limit(size).skip((page-1)*size).populate('cate')
    var total=await qstmodel.find({title:{$regex:reg}}).count()
  }else if(req.query.status && req.query.title==''){
    // 查询状态 不搜索标题时
    var s=parseInt(req.query.status)
    var d=await qstmodel.find({status:s}).limit(size).skip((page-1)*size).populate('cate')
    var total=await qstmodel.find({status:s}).count()
  }else if(req.query.title && req.query.status){
    // 查询题目 当搜索题目且选择状态时
    var s=parseInt(req.query.status)
    var reg = new RegExp(req.query.title,'i')
    var d=await qstmodel.find({title:{$regex:reg},status:s}).limit(size).skip((page-1)*size).populate('cate')
    var total=await qstmodel.find({title:{$regex:reg},status:s}).count()

  }else if(req.query.wtitle){
    // 未通过题目的查询
    console.log(1111111)
    var reg = new RegExp(req.query.wtitle,'i')
    var d=await qstmodel.find({title:{$regex:reg},status:2}).limit(size).skip((page-1)*size).populate('cate')
    var total=await qstmodel.find({title:{$regex:reg},status:2}).count()
  }else if(req.query.xqid){
    // 查询相应的题目和解析
    var d=await qstmodel.findOne({_id:req.query.xqid}).populate('cate')
    var total=d.length
  }else if(req.query.tong){
    // 只要已发布的
    var d=await qstmodel.find({status:1}).limit(size).skip((page-1)*size).populate('cate')
    var total=await qstmodel.find({status:1}).count()
  }else if(req.query.wei){
    // 只要已发布的
    var d=await qstmodel.find({status:2}).limit(size).skip((page-1)*size).populate('cate')
    var total=await qstmodel.find({status:2}).count()
  }else{
    var d=await qstmodel.find().limit(size).skip((page-1)*size).populate('cate')
    var total=await qstmodel.find().count()
  }
  res.json({"message":"获取成功","code":200,"data":d,"total":total})
})
// 修改题目
router.put('/question/:_id',async function(req,res){
  var data=await qstmodel.updateOne(req.params,req.body)
  res.json({"message":"修改成功","code":200})
})
// 删除题目
router.delete('/question/:_id',async function(req,res){
  if(req.user.data!='admin'){
    res.json({"message":"没有权限","code":400})
  }else{
    var data=await qstmodel.deleteOne(req.params)
    res.json({"message":"删除成功","code":200})
  }
})
// 添加预约信息
router.post('/mian',async function(req,res){
  var d=await mianmodel.create(req.body)
  res.json({"message":"添加成功","code":200})
})
// 获取预约信息
router.get('/mian',async function(req,res){
  var page=parseInt(req.query.page) 
  var size=parseInt(req.query.size)
  console.log(req.query)
  if(req.query.search && req.query.searname==''){
    var reg=new RegExp(req.query.search,'i')
    var d=await mianmodel.find({company:{$regex:reg}}).limit(size).skip((page-1)*size)
    var total=await mianmodel.find({company:{$regex:reg}}).count()
  }else if(req.query.search=='' && req.query.searname){
    var reg=new RegExp(req.query.searname,'i')
    var d=await mianmodel.find({name:{$regex:reg}}).limit(size).skip((page-1)*size)
    var total=await mianmodel.find({name:{$regex:reg}}).count()
  }else if(req.query.search && req.query.searname){
    var reg=new RegExp(req.query.searname,'i')
    var reg1=new RegExp(req.query.search,'i')
    var d=await mianmodel.find({name:{$regex:reg},company:{$regex:reg1}}).limit(size).skip((page-1)*size)
    var total=await mianmodel.find({name:{$regex:reg},company:{$regex:reg1}}).count()
  }else if(req.query.searname1){
    var reg=new RegExp(req.query.searname1,'i')
    var d=await mianmodel.find({name:{$regex:reg},status:0}).limit(size).skip((page-1)*size)
    var total=await mianmodel.find({name:{$regex:reg},status:0}).count()
  }else if(req.query.searname2){
    var reg=new RegExp(req.query.searname2,'i')
    var d=await mianmodel.find({name:{$regex:reg},status:1}).limit(size).skip((page-1)*size)
    var total=await mianmodel.find({name:{$regex:reg},status:1}).count()
  }else if(req.query.wei){
    // 只要未审核得
    var d=await mianmodel.find({status:0}).limit(size).skip((page-1)*size)
    var total=await mianmodel.find({status:0}).count()
  }else if(req.query.yi){
    // 只要已审核通过得
    var d=await mianmodel.find({status:1}).limit(size).skip((page-1)*size)
    var total=await mianmodel.find({status:1}).count()
  }else if(req.query._id){
    // 详情
    var d=await mianmodel.findOne({_id:req.query._id})
    var total=await mianmodel.findOne({_id:req.query._id}).count()
  }else{
    var d=await mianmodel.find().limit(size).skip((page-1)*size)
    var total=await mianmodel.find().count()
  }
  res.json({"message":"获取成功","code":200,"data":d,"total":total})
})
// 删除预约信息
router.delete('/mian/:_id',async function(req,res){
  if(req.user.data!='admin'){
    res.json({"message":"没有权限","code":400})
  }else{
    var data=await mianmodel.deleteOne(req.params)
    res.json({"message":"删除成功","code":200})
  }
})

// 修改面试状态
router.put("/mian/:_id",async function(req,res){
  var data=await mianmodel.updateOne(req.params,req.body)
  res.json({"message":"修改成功","code":200})
})
//上传录音
router.post('/mianfu',upload.single('file'),async function(req,res){
  console.log(req.body)
  console.log(req.file)
  var ext = path.extname(req.file.originalname)
  fs.rename(req.file.path,req.file.path+ext,function(err){

      if(!err){
        console.log("图片重命名成功")
      }
  })
  var data=await mianmodel.updateOne({_id:req.body.id},{lu:'http://127.0.0.1:3000/media/'+req.file.filename+ext})
  res.json(1)
})
// 添加试卷
router.post('/test',async function(req,res){
  var data=await testmodel.create(req.body)
  res.json({"message":"添加成功","code":200,"data":data})
})
// 获取试卷
router.get('/test',async function(req,res){
  var page=parseInt(req.query.page) 
  var size=parseInt(req.query.size)
  if(req.query.sjname){
    var reg=new RegExp(req.query.sjname,'i')
    var data=await testmodel.find({sjname:{$regex:reg}}).limit(size).skip((page-1)*size)
    var total=await testmodel.find({sjname:{$regex:reg}}).count()
  }else if(req.query.id){
    var data=await testmodel.findOne({_id:req.query.id})
    var total=await testmodel.findOne({_id:req.query.id}).count()
  }else{
    var data=await testmodel.find().limit(size).skip((page-1)*size)
    var total=await testmodel.find().count()
  }
  res.json({"message":"获取成功","code":200,"data":data,"total":total})
})

// 交卷
router.post('/kao',async function(req,res){
  var data=await kaomodel.create(req.body)
  res.json({"message":"交卷成功","code":200})
})
// 获取考试信息
router.get('/kao',async function(req,res){
  var page=parseInt(req.query.page) 
  var size=parseInt(req.query.size)
  if(req.query.name){
    var reg=new RegExp(req.query.name,'i')
    var data=await kaomodel.find({name:{$regex:reg}}).limit(size).skip((page-1)*size)
    var total=await kaomodel.find({name:{$regex:reg}}).count()
  }else if(req.query._id){
    var data=await kaomodel.find({_id:req.query._id}).limit(size).skip((page-1)*size).populate('testid')
    var total=await kaomodel.find({_id:req.query._id}).count()
  }else{
    var data=await kaomodel.find().limit(size).skip((page-1)*size).populate('testid')
    var total=await kaomodel.find().count()
  }
  res.json({"message":"获取成功","code":200,"data":data,"total":total})

})
// 修改面试状态
router.put("/kao/:_id",async function(req,res){
  var data=await kaomodel.updateOne(req.params,req.body)
  res.json({"message":"修改成功","code":200})
})
module.exports = router;
